﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Depot;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using BasicInformation.Infrastructure.Interface;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Depot
{
    /// <summary>
    /// 添加仓库管理处理类
    /// </summary>
    public class AddDepotHandler : IRequestHandler<AddDepotCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly ILogger<AddDepotHandler> logger;
        private readonly DatabaseContext db;

        public AddDepotHandler(IMapper mapper,ILogger<AddDepotHandler> logger, DatabaseContext db)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.db = db;
        }
        public async Task<ApiResult<int>> Handle(AddDepotCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result =new ApiResult<int>();
            var depot=mapper.Map<DepotModel>(request);
           var model= db.SqlSugar.Queryable<DepotModel>().Where(x=>x.DepotCode==request.DepotCode).First();
            if (model!=null)
            {
                result.Msg = "该仓库管理已存在，请重新输入";
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
                return await Task.FromResult(result);
            }
            int r = await db.SqlSugar.Insertable(depot).ExecuteReturnIdentityAsync();
            if (r > 0)
            {
                result.Msg = "仓库管理添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "仓库管理添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
